using Microsoft.EntityFrameworkCore;
using UwinEducation.Application.Common.Interfaces;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;
using UwinEducation.Infrastructure.Repositories;


namespace UwinEducation.Application.Services
{
    public class PermissionService : IPermissionService
    {
        private readonly ICacheService _cacheService;
        private readonly IUserRepository _userRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly IPermissionRepository _permissionRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;

        public PermissionService(
            ICacheService cacheService, 
            IUserRepository userRepository, 
            IRoleRepository roleRepository, 
            IPermissionRepository permissionRepository, 
            IRolePermissionRepository rolePermissionRepository)
        {
            _cacheService = cacheService;
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _permissionRepository = permissionRepository;
            _rolePermissionRepository = rolePermissionRepository;
        }

        public async Task<bool> UserHasPermissionsAsync(Guid userId, string[] permissions)
        {
            var userPermissions = await GetUserPermissionsAsync(userId);
            return permissions.All(p => userPermissions.Contains(p));
        }

        public async Task<IEnumerable<string>> GetUserPermissionsAsync(Guid userId)
        {
            var cacheKey = $"user_permissions:{userId}";

            // 尝试从缓存获取
            var cachedPermissions = await _cacheService.GetAsync<string[]>(cacheKey);
            if (cachedPermissions != null)
            {
                return cachedPermissions;
            }
            // 使用仓储方法获取权限
            var permissions = await _rolePermissionRepository.GetPermissionCodesByUserIdAsync(userId);

            //var permissions = await _context.UserRoles
            //    .Where(ur => ur.UserId == userId)
            //    .Join(_context.RolePermissions,
            //        ur => ur.RoleId,
            //        rp => rp.RoleId,
            //        (ur, rp) => rp.PermissionCode)
            //    .Distinct()
            //    .ToArrayAsync();

            // 存入缓存
            await _cacheService.SetAsync(cacheKey, permissions, TimeSpan.FromMinutes(30));

            return permissions;
        }

        public async Task<bool> HasPermissionAsync(Guid userId, string permissionCode)
        {
            // 使用仓储方法检查权限
            return await _rolePermissionRepository.UserHasPermissionAsync(userId, permissionCode);
        }
    }
}